package cn.com.zero.db.service;


import cn.com.zero.base.util.SpringApplicationUtil;
import cn.com.zero.db.config.DynamicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 动态数据源业务类
 * @createTime 2022/7/15 15:02
 */
public class DynamicDataSourceService {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceService.class);

    private static final ThreadLocal<String> dbKeys = ThreadLocal.withInitial(() -> null);

    /**
     * 添加数据源到动态数据源对象
     *
     * @param name       数据源的key
     * @param dataSource 数据源对象
     */
    public static void addDataSource(String name, DataSource dataSource) {
        DynamicDataSource dynamicDataSource = SpringApplicationUtil.getBean(DynamicDataSource.class);
        dynamicDataSource.addDataSource(name, dataSource);
        dynamicDataSource.afterPropertiesSet();

        log.info("添加了数据源:{}", name);
    }

    /**
     * 切换数据源
     */
    public static void switchDb(String dbKey) {
        dbKeys.set(dbKey);
    }

    /**
     * 重置数据源
     */
    public static void resetDb() {
        dbKeys.remove();
    }

    /**
     * 获取当前数据源
     */
    public static String currentDb() {
        return dbKeys.get();
    }
}
